#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from db import get_conn

def check_customer_data():
    """直接检查数据库中的客户数据"""
    print("🔍 直接检查数据库中的客户数据...")
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 查询所有客户数据
        cursor.execute("SELECT * FROM userinfo ORDER BY customerID")
        customers = cursor.fetchall()
        
        print(f"\n✅ 数据库中共有 {len(customers)} 个客户:")
        print("-" * 80)
        
        for customer in customers:
            print(f"客户编号: {customer['customerID']}")
            print(f"客户姓名: '{customer['customerName']}' (类型: {type(customer['customerName'])})")
            print(f"身份证号: {customer['PID']}")
            print(f"联系电话: {customer['telephone']}")
            print(f"联系地址: {customer['address']}")
            print("-" * 80)
        
        cursor.close()
        conn.close()
        
    except Exception as e:
        print(f"❌ 数据库查询失败: {e}")

def fix_customer_names():
    """修复客户姓名为None的问题"""
    print("\n🔧 修复客户姓名为None的问题...")
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 查找客户姓名为None的记录
        cursor.execute("SELECT customerID, customerName FROM userinfo WHERE customerName IS NULL OR customerName = 'None'")
        null_customers = cursor.fetchall()
        
        if null_customers:
            print(f"发现 {len(null_customers)} 个客户姓名为None的记录:")
            for customer in null_customers:
                print(f"  客户编号: {customer['customerID']}, 客户姓名: '{customer['customerName']}'")
            
            # 更新这些记录，将None改为空字符串
            cursor.execute("UPDATE userinfo SET customerName = '' WHERE customerName IS NULL OR customerName = 'None'")
            updated_count = cursor.rowcount
            
            conn.commit()
            print(f"✅ 成功更新 {updated_count} 条记录")
        else:
            print("✅ 没有发现客户姓名为None的记录")
        
        cursor.close()
        conn.close()
        
    except Exception as e:
        print(f"❌ 修复失败: {e}")

if __name__ == "__main__":
    check_customer_data()
    fix_customer_names()
    print("\n🔍 修复后再次检查:")
    check_customer_data() 